package com.jxc.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jxc.dao.BaseDaoI;
import com.jxc.model.po.Goods;
import com.jxc.model.po.GoodsRepertory;
import com.jxc.model.po.Orderlist;
import com.jxc.model.po.OrderlistItem;
import com.jxc.model.po.Repertory;
import com.jxc.model.po.User;
import com.jxc.model.vo.DataGrid;
import com.jxc.model.vo.VGoods;
import com.jxc.model.vo.VGoodsRepertory;
import com.jxc.model.vo.VOrderlist;
import com.jxc.model.vo.VOrderlistItem;
import com.jxc.service.OrderServiceI;

@Service("orderService")
public class OrderServiceImpl implements OrderServiceI {
	@Autowired
	private BaseDaoI<Orderlist> orderDao;
	@Autowired
	private BaseDaoI<OrderlistItem> itemDao;
	@Autowired
	private BaseDaoI<Goods> goodsDao;
	@Autowired
	private BaseDaoI<GoodsRepertory> goodsreperDao;

	@Override
	public DataGrid datagrid(VOrderlist vOrderlist) {
		DataGrid dg = new DataGrid();
		dg.setRows(this.changeModel(this.find(vOrderlist)));
		dg.setTotal(this.total(vOrderlist));
		return dg;
	}

	private List<VOrderlist> changeModel(List<Orderlist> orderlists) {
		List<VOrderlist> vOrderlists = new ArrayList<VOrderlist>();
		if (orderlists != null && orderlists.size() > 0) {
			for (Orderlist orderlist : orderlists) {
				VOrderlist vOrderlist = new VOrderlist();
				BeanUtils.copyProperties(orderlist, vOrderlist);
				if (orderlist.getRepertory() != null) {
					Repertory repertory = orderlist.getRepertory();
					vOrderlist.setRid(repertory.getId());
					vOrderlist.setRname(repertory.getName());
				}
				if (orderlist.getUser() != null) {
					User user = orderlist.getUser();
					vOrderlist.setUid(user.getId());
					vOrderlist.setUname(user.getUsername());
				}
				vOrderlists.add(vOrderlist);
			}
		}
		return vOrderlists;
	}

	private List<Orderlist> find(VOrderlist vOrderlist) {
		String hql = "from Orderlist t where t.isDeleted = false ";

		List<Object> values = new ArrayList<Object>();
		hql = addWhere(vOrderlist, hql, values);

		if (vOrderlist.getSort() != null && vOrderlist.getOrder() != null) {
			hql += " order by " + vOrderlist.getSort() + " "
					+ vOrderlist.getOrder();
		}
		
		return orderDao.find(hql, values, vOrderlist.getPage(), vOrderlist
				.getRows());
	}

	private Long total(VOrderlist vOrderlist) {
		String hql = "select count(*) from Orderlist t where t.isDeleted=false ";
		List<Object> values = new ArrayList<Object>();
		hql = addWhere(vOrderlist, hql, values);
		return orderDao.count(hql, values);
	}

	private String addWhere(VOrderlist vOrderlist, String hql,
			List<Object> values) {
		if(vOrderlist.getId()!=null&&vOrderlist.getId()!=0){
			hql += " and t.id = ? ";
			values.add(vOrderlist.getId());
		}
		if (vOrderlist.getDateStart() != null) {
			hql += " and t.date >= ? ";
			values.add(vOrderlist.getDateStart());
		}
		if (vOrderlist.getDateEnd() != null) {
			hql += " and t.date <= ? ";
			values.add(vOrderlist.getDateEnd());
		}
		if (vOrderlist.getRid() != null&&!vOrderlist.getRid().equals("")) {
			hql += " and t.repertory.id  = ? ";
			values.add(vOrderlist.getRid());
		}
		if (vOrderlist.getUpid() != null&&!vOrderlist.getUpid().equals("")) {
			hql += " and t.user.user.id  = ? ";
			values.add(vOrderlist.getUpid());
		}else if (vOrderlist.getUid() != null&&!vOrderlist.getUid().equals("")) {
			hql += " and t.user.id  = ? ";
			values.add(vOrderlist.getUid());
		}
		/*else{
			hql += " and t.repertory.id is null ";
		}*/
		return hql;
	}

	@Override
	public void delete(String ids) {
		if (ids != null) {
			for (String id : ids.split(",")) {
				if (!id.trim().equals("0")) {
					Orderlist orderlist = orderDao.get(Orderlist.class, Long
							.parseLong(id.trim()));
					if (orderlist != null) {
						orderlist.setIsDeleted(true);
						orderDao.update(orderlist);
					}
				}
			}
		}

	}

	@Override
	public void save(VOrderlist vOrderlist,String items) {
		Orderlist orderlist = new Orderlist();
		BeanUtils.copyProperties(vOrderlist, orderlist);
		if (vOrderlist.getRid() != null) {
			orderlist.setRepertory(new Repertory(vOrderlist.getRid()));
		}
		if (vOrderlist.getUid() != null) {
			orderlist.setUser(new User(vOrderlist.getUid()));
		}
		orderlist.setIsDeleted(false);
		if(vOrderlist.getDate()!=null){
			java.sql.Timestamp time = new java.sql.Timestamp(new java.util.Date().getTime());
			int h = time.getHours();//时
			int f = time.getMinutes();//分
			int m = time.getSeconds();//秒
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			//年月日
			int y = vOrderlist.getDate().getYear()+1900;
			int yf = vOrderlist.getDate().getMonth()+1;
			int day = vOrderlist.getDate().getDate();
			String str = y+"-"+yf+"-"+day+" "+h+":"+f+":"+m;	
			try {
				Date d = sdf.parse(str);
				orderlist.setDate(d);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		
		try{
			this.orderDao.save(orderlist);
			
			String[] objs = items.split(",");
			Double total=0d;
			if(objs.length>0){
				for(int i=0;i<objs.length;){
					Goods goods = goodsDao.get(Goods.class, Long.parseLong(objs[i]));
					if(goods!=null){
					Integer num = Integer.parseInt(objs[i+1]);
					if(num>0){
					Double buyprice = Double.parseDouble(objs[i+1+1]);
						OrderlistItem item = new OrderlistItem();
						item.setBuyPrice(buyprice);
						if(buyprice!=goods.getBuyPrice()){
							goods.setBuyPrice(buyprice);
							goodsDao.update(goods);
							item.setGoods(goods);
						}
						item.setNum(num);
						item.setOrderlist(orderlist);
						item.setTotal(num*item.getBuyPrice());
						itemDao.save(item);
						total+=item.getTotal();
//						if (goods.getAmount()==null) {
//							goods.setAmount(num);
//						}else{
//							goods.setAmount(goods.getAmount()+num);
//						}
//						goods.setOrderTotal(goods.getOrderTotal()+num);
//						goodsDao.update(goods);
						if(num==null){
							num = 0;
						}
						String sql = "select t from GoodsRepertory t where t.goods.id="+goods.getId()+" and t.repertory.id="+vOrderlist.getRid();
						List<GoodsRepertory> gr = goodsreperDao.find(sql);
						if(gr.size()==0){
							GoodsRepertory cr = new GoodsRepertory();
							cr.setGoods(goods);
							cr.setRepertory(new Repertory(vOrderlist.getRid()));
							cr.setNum(num);       
							goodsreperDao.save(cr);
						}else {
							for(GoodsRepertory ff : gr){
								GoodsRepertory cr = goodsreperDao.get(GoodsRepertory.class, ff.getId());
								cr.setNum(cr.getNum()+num);
								goodsreperDao.update(cr);
							}
						}
					}
					}
					i=i+3;
				}
			}
			orderlist.setTotal(total);
			orderDao.update(orderlist);
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}

	@Override
	public List<VOrderlist> search(VOrderlist vOrderlist) {
		return changeModel(find(vOrderlist));
	}

	public DataGrid datagridItems(VOrderlist vOrderlist){
		DataGrid dg = new DataGrid();
		dg.setRows(this.getItems(vOrderlist));
		dg.setTotal(totalItems(vOrderlist));
		return dg;
	}
	@Override
	public List<VOrderlistItem> getItems(VOrderlist vOrderlist) {
		String hql = "from OrderlistItem t where t.orderlist.id = ? ";
		List<Object> values = new ArrayList<Object>();
		values.add(vOrderlist.getId());
		List<OrderlistItem> items = itemDao.find(hql, values,vOrderlist.getPage(), vOrderlist
				.getRows());
		return changeModelForItem(items);
	}
	
	private Long totalItems(VOrderlist vOrderlist){
		String hql = "select count(*) from OrderlistItem t where t.orderlist.id = ? ";
		List<Object> values = new ArrayList<Object>();
		values.add(vOrderlist.getId());
		return itemDao.count(hql, values);
	}
	private List<VOrderlistItem> changeModelForItem(List<OrderlistItem> items){
		List<VOrderlistItem> results = new ArrayList<VOrderlistItem>();
		if (items != null && items.size() > 0) {
			for (OrderlistItem item : items) {
				VOrderlistItem vOrderlistItem = new VOrderlistItem();
				BeanUtils.copyProperties(item, vOrderlistItem);
				if (item.getGoods() != null) {
					Goods goods = item.getGoods();
					vOrderlistItem.setBarcode(goods.getBarcode());
					vOrderlistItem.setGid(goods.getId());
					vOrderlistItem.setGname(goods.getName());
					vOrderlistItem.setBname(goods.getBrand().getName());
					vOrderlistItem.setColor(goods.getColor());
					vOrderlistItem.setGtname(goods.getGoodsType().getName());
					vOrderlistItem.setSize(goods.getSize());
					vOrderlistItem.setUnit(goods.getUnit());
					vOrderlistItem.setGtype(goods.getType());
				}if(item.getOrderlist()!=null){
					vOrderlistItem.setRid(item.getOrderlist().getRepertory().getId());
				}
				results.add(vOrderlistItem);
			}
		}
		return results;
	}

	@Override
	public List<Object[]> findByGoods(VGoodsRepertory vg, String order) {
		String hql = "select  t.num,t.buy_price from rkgl_orderlist_item t, rkgl_orderlist s " +
				" where t.orderlist_id=s.id  " ;
		if(vg.getRid()!=null){
			hql += " and s.repertory_id="+vg.getRid(); 
		} 
		if(vg.getGid()!=null){
			hql += " and t.goods_id="+vg.getGid(); 
		} 
		hql += " order by  s.date "+order;
		return  itemDao.findBySql(hql);
	}

	
}
